package com.zr.daoImpl;
/**
 * 
 * @author CY
 *
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.zr.dao.FunctionDao;
import com.zr.util.JDBCUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class FunctionDaoImpl implements FunctionDao{
	@Override
	public JSONArray getfuncsByParentId(int parentId) {
		JSONArray   funcs =  new JSONArray();
		Connection  con   =  JDBCUtil.getConnection();
		StringBuffer  sql = new StringBuffer("select * from function where pid=?");
		try {
			PreparedStatement   pst =  con.prepareStatement(sql.toString());
			pst.setInt(1, parentId);
			ResultSet  rs  =  pst.executeQuery();
			while(rs.next()){
				  JSONObject  func =  new JSONObject();
				  func.put("id", rs.getInt("fid"));
				  func.put("text", rs.getString("fname"));
				  func.put("state", rs.getString("fstate"));
				  JSONObject  attr  = new JSONObject();
				  attr.put("furl", rs.getString("furl"));
				  func.put("attributes", attr);
				  funcs.add(func);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return funcs;
		
	}

	@Override
	public JSONArray getCurrentUserFuncsByParentId(int parentId) {
		JSONArray   userfuncs  = this.getfuncsByParentId(parentId);
		for (int i = 0; i < userfuncs.size(); i++) {
			  String state = userfuncs.getJSONObject(i).getString("state");
			  if("open".equals(state)){
				     continue;
			  }else{
				   int currentId = userfuncs.getJSONObject(i).getInt("id");
				   JSONArray   children  =  this.getCurrentUserFuncsByParentId(currentId);
				   userfuncs.getJSONObject(i).put("children", children);
			  }
		}
		
		
		return  userfuncs;
		
	}
	
}
